package com.example.project.projectspringcloud.controller.front.order;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.common.OperationException;
import com.example.project.projectspringcloud.controller.BaseController;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.order.Order;
import com.example.project.projectspringcloud.entity.order.OrderReceipt;
import com.example.project.projectspringcloud.entity.sys.Area;
import com.example.project.projectspringcloud.entity.user.User;
import com.example.project.projectspringcloud.service.order.OrderReceiptService;
import com.example.project.projectspringcloud.service.order.OrderService;
import com.example.project.projectspringcloud.service.sys.SysAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Api(tags = "用户发票Controller")
@Controller
@RequestMapping(value = "/personal/receipt")
public class ReceiptController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(ReceiptController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderReceiptService orderReceiptService;

    @Autowired
    private SysAreaService sysAreaService;

    @ApiOperation(value = "发票列表", notes = "返回发票列表")
    @GetMapping(value = {"", "/list"})
    public String list(Page page, Model model) {
        // 获取已完成的订单
        Order order = new Order();
        order.setUserId(super.getCurrentUserId());
        order.setStatus(1);
        List<Order> orders = orderService.list(page, order);
        model.addAttribute("page", new Page<Order>(orders));

        return isMobile() ? "m/content/order/receipt-list" : "content/order/receipt-list";
    }

    @ApiOperation(value = "API发票列表", notes = "返回发票列表")
    @GetMapping(value = "/api/list")
    public String content(@RequestParam("searchWord") String searchWord,
            Page page, Model model) {
        // 获取已完成的订单
        Order order = new Order();
        order.setUserId(super.getCurrentUserId());
        order.setStatus(1);
        order.setSearchWord(searchWord);
        List<Order> orders = orderService.list(page, order);
        model.addAttribute("page", new Page<Order>(orders));

        return "content/order/receipt-list-content";
    }

    @ApiOperation(value = "发票申请", notes = "返回发票申请页面")
    @GetMapping(value = "/ready/{orderId}")
    public String ready(@PathVariable("orderId") Integer orderId, Model model, RedirectAttributes redirectAttributes) {

        Order order = new Order();
        order.setUserId(super.getCurrentUser().getId());
        order.setId(orderId);
        order = orderService.get(order);
        model.addAttribute("order", order);

        // 城市信息
        Area entity = new Area();
        entity.setIsOpen(1);
        List<Area> areas = sysAreaService.list(entity, null);
        model.addAttribute("areas", areas);

        return isMobile() ? "m/content/order/receipt-apply-form" : "content/order/receipt-apply";
    }

    @ApiOperation(value = "发票申请", notes = "返回发票申请页面")
    @PostMapping(value = "/apply/{orderId}")
    public String apply(@PathVariable("orderId") Integer orderId,
                        OrderReceipt receipt, Model model, RedirectAttributes redirectAttributes) {

        model.addAttribute("receipt", receipt);

        Order order = new Order();
        order.setUserId(super.getCurrentUser().getId());
        order.setId(orderId);
        order = orderService.get(order);

        // 如果订单不存在发票, 则返回创建发票页面
        if (order == null) {
            redirectAttributes.addFlashAttribute("error", super.translateI18N(Constants.Message.ORDER_DOES_NOT_EXIST));
            return String.format("redirect:/personal/receipt/ready/%s", order.getId());
        } else {
            if (order.getOrderReceipt() != null) {
                redirectAttributes.addFlashAttribute("error", super.translateI18N(Constants.Tip.ORDER_RECEIPT_ALREADY_EXIST));
                return String.format("redirect:/personal/receipt/ready/%s", order.getId());
            }
            try {
                receipt.setOrder(order.getId());
                receipt.setPrice(order.getTotalPrice());
                orderReceiptService.create(receipt);
                return "redirect:/personal/receipt";
            } catch (OperationException e) {
                logger.error("ReceiptController - apply", e);
                redirectAttributes.addFlashAttribute("error", e.getLocalizedMessage());
                return String.format("redirect:/personal/receipt/ready/%s", order.getId());
            }
        }
    }

    @ApiOperation(value = "发票详情", notes = "返回发票详情页面")
    @GetMapping(value = "/detail/{orderId}")
    public String detail(@PathVariable("orderId") Integer orderId, Model model) {
        Order order = new Order();
        order.setUserId(super.getCurrentUser().getId());
        order.setId(orderId);
        order = orderService.get(order);
        model.addAttribute("orderReceipt", order.getOrderReceipt());
        return isMobile() ? "m/content/order/receipt-apply-detail" : "content/order/receipt-details";
    }
}
